package com.djhu.freepartner.web.control;

import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.web.control.model.VerifiyCode;
import com.djhu.freepartner.web.service.VerifiyCodeService;
import com.djhu.freepartner.web.support.VerifiyCodeGenerator;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class VerificationCodeControl {
    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeControl.class.getName());

    @Autowired
    private VerifiyCodeService verifiyCodeService;

    @ApiOperation(value="验证码生成", notes="验证码生成接口")
    @RequestMapping(value = "/verificationCode", method = RequestMethod.POST)
    public RestRsp verificationCode(@RequestParam(value = "width" ,defaultValue = "70") Integer width,@RequestParam(value = "height" ,defaultValue = "35") Integer height,@RequestParam(value = "with_prefix",defaultValue = "true") Boolean withPrefix){

        if (height < 0 || width <0){
            logger.error("height and width must larger than 0");
        }

        RestRsp restRsp = new RestRsp();
        VerifiyCode verifiyCode =  verifiyCodeService.create(width,height);
        if (verifiyCode == null){
            logger.error("验证码生成失败");
            restRsp.setMsg("验证码生成失败  稍后再试");
            restRsp.setCode(Status.VERIFY_CODE_FAIL.getCode());
        }else {
            restRsp.setData(verifiyCode);
            restRsp.setCode(Status.SUCCESS.getCode());
        }
        return restRsp;
    }


    public static void main(String[] args) throws IOException {
        VerifiyCodeGenerator verifiyCodeGenerator = new VerifiyCodeGenerator(70,35);
        BufferedImage image = verifiyCodeGenerator.getImage();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        ImageIO.write(image,"png",byteArrayOutputStream);
        byte[] byteArray =  byteArrayOutputStream.toByteArray();
        String text = verifiyCodeGenerator.getText();
//
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 =  encoder.encodeBuffer(byteArray).trim();
//
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
        System.out.println(png_base64);
        System.out.println(text);
    }
}
